package com.fin.zw.intelligentbot.service;

import com.alibaba.fastjson.JSON;
import com.fin.zw.intelligentbot.entity.CorpusInfo;
import com.fin.zw.intelligentbot.entity.QVerbalNode;
import com.fin.zw.intelligentbot.entity.VerbalNode;
import com.fin.zw.intelligentbot.entity.VerbalTrick;
import com.fin.zw.intelligentbot.model.verbal.Attitude;
import com.fin.zw.intelligentbot.model.verbal.NodeInfo;
import com.fin.zw.intelligentbot.model.verbal.Sentence;
import com.fin.zw.intelligentbot.repository.VerbalNodeRepository;
import com.fin.zw.intelligentbot.repository.VerbalTrickRepository;
import com.fin.zw.intelligentbot.util.JsonToTree;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service("verbalService")
public class VerbalService {

    private final static Logger log = LoggerFactory.getLogger(VerbalService.class);

    @Autowired
    private VerbalNodeRepository verbalNodeRepository;

    @Autowired
    private VerbalTrickRepository verbalTrickRepository;

    /**
     * 根据话术id查询对应的节点信息，并转换为json
     *Object taskMap = JSONObject.toJSON(map);
     * @param verbalId
     */
    public void verbalNodeToJson(String verbalId) {
        log.info("开始获取话术信息....");
        Optional<VerbalTrick> optional = verbalTrickRepository.findById(verbalId);
        if (!optional.isPresent()) {
            throw new RuntimeException("选择的话术信息不存在");
        }
        VerbalTrick verbalTrick = optional.get();
        Iterator<VerbalNode> iterator = verbalNodeRepository.findAll(QVerbalNode.verbalNode.verbalId.eq(verbalId)).iterator();
        List<VerbalNode> verbalNodes = Lists.newArrayList(iterator);
        //获取父id为空的集合
        List<NodeInfo> list = verbalNodes.stream().map(t -> {
            return createNodeInfo(t, verbalTrick.getName());
        }).collect(Collectors.toList());

        List<NodeInfo> first = getKeyNull(list);
        list.removeAll(first);
        Map<String, List<NodeInfo>> collect = list.stream().collect(Collectors.groupingBy(NodeInfo::getPid));
        NodeInfo info = getFirstNode(first, collect);
        info.setPid("1");
        list.add(info);
        NodeInfo nodeInfo = JsonToTree.getParentNodeInfo(list, info);
        Map<String, Object> map = new HashMap<>();
        map.put("flow", nodeInfo);
        first.remove(info);
        Map<String, NodeInfo> qestion = new HashMap<>();
        for (NodeInfo node : first) {
            int count = 1;
            if (!node.getId().equals(info.getId())) {
                qestion.put("FAQ" + count, node);
            }
            count++;
        }
        map.put("qestionAnnswers", qestion);

        String result = JSON.toJSONString(map, true);
        System.out.println(result);
    }

    /**
     * 获取key值为空的对象
     *
     * @param nodeInfoList
     * @return
     */
    public List<NodeInfo> getKeyNull(List<NodeInfo> nodeInfoList) {
        List<NodeInfo> list = new ArrayList<>();
        for (NodeInfo nodeInfo : nodeInfoList) {
            if (StringUtils.isBlank(nodeInfo.getPid())) {
                list.add(nodeInfo);
            }
        }
        return list;
    }

    /**
     * 实体转换
     *
     * @param t
     * @param flow
     * @return
     */
    public NodeInfo createNodeInfo(VerbalNode t, String flow) {
        NodeInfo nodeInfo = new NodeInfo();
        nodeInfo.setId(t.getId());
        nodeInfo.setPid(t.getParentId());
        nodeInfo.setFlowSign(t.getFlowSign().toString().toLowerCase());
        nodeInfo.setIsEnd(t.getIsEnd().toString().toLowerCase());
        if (Objects.nonNull(t.getAttitude())) {
            Attitude attitude = new Attitude();
            BeanUtils.copyProperties(t.getAttitude(), attitude);
            nodeInfo.setAttitude(attitude);
        }
        if (t.getCorpusInfoSet() != null) {
            Map<String, Sentence> sentences = new HashMap<>();
            for (CorpusInfo corpusInfo : t.getCorpusInfoSet()) {
                int i = 1;
                Sentence sen = new Sentence();
                sen.setContent(corpusInfo.getContent());
                sen.setType(corpusInfo.getType().toString().toLowerCase());
                sen.setFile(flow);
                sen.setCan_break(t.getNeedBreak().toString().toLowerCase());
                sentences.put("sentence" + i, sen);
                i++;
            }
            nodeInfo.setText(sentences);
        }
        return nodeInfo;
    }

    /**
     * 获取开始的节点
     *@param roots (父id为空的)
     * @param map
     * @return
     */
    public NodeInfo getFirstNode(List<NodeInfo> roots, Map<String, List<NodeInfo>> map) {
        for (NodeInfo nodeInfo : roots) {
            if (map.containsKey(nodeInfo.getId()))
                return nodeInfo;
        }
        return null;
    }
}
